package com.songtech.shiro.filter;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

public class UrlAuthenticationFilter extends AccessControlFilter{

	private static String LOGIN_URL = "/login.html";
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		
		Subject subject = getSubject(request, response);
		if(null != mappedValue){
			String[] arra = (String[])mappedValue;
			for (String permission : arra) {
				if(subject.isPermitted(permission)){
					return Boolean.TRUE;
				}
			}
		}
		 HttpServletRequest httpRequest = (HttpServletRequest) request;
		 String uri = httpRequest.getRequestURI();
		 String basePath = httpRequest.getContextPath();
			if(null != uri && uri.startsWith(basePath)){
				uri = uri.replace(basePath, "");
			}
			if(subject.isPermitted(uri)){
				return Boolean.TRUE;
			}
		return false;
	}

	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		Subject subject = getSubject(request, response);  
		HttpServletRequest httpRequest = (HttpServletRequest) request;
        if (null == subject.getPrincipal()) {//表示没有登录，重定向到登录页面  
            saveRequest(request);  
            WebUtils.issueRedirect(request, response,LOGIN_URL);  
        } else {  
        	String httpHeader = httpRequest.getHeader("x-requested-with");
			if(StringUtils.isNotBlank(httpHeader) && ("XMLHttpRequest").equalsIgnoreCase(httpHeader)){
				PrintWriter printWriter = response.getWriter();
				Map<String,String> resultMap = new HashMap<String, String>();
				resultMap.put("not_auth", "当前用户无权限");
				//printWriter.write(JSONObject.fromObject(resultMap).toString());
				printWriter.flush();
	            printWriter.close();
	            return false;
			}
        }  
        return true;
    }
}
